#include <iostream>
#include "httplib.h"
#include "contacts.pb.h"
#include "Exception.h"
using namespace httplib;
using namespace std;
static unsigned int random_char()
{
    // ⽤于随机数引擎获得随机种⼦
    std::random_device rd;
    // mt19937是c++11新特性，它是⼀种随机数算法，⽤法与rand()函数类似，但是mt19937具有速度快，周期⻓的特点
    // 作⽤是⽣成伪随机数
    std::mt19937 gen(rd());
    // 随机⽣成⼀个整数i 范围[0, 255]
    std::uniform_int_distribution<> dis(0, 255);
    return dis(gen);
}
// ⽣成 UUID （通⽤唯⼀标识符）
static std::string generate_hex(const unsigned int len)
{
    std::stringstream ss;
    // ⽣成 len 个16进制随机数，将其拼接⽽成
    for (auto i = 0; i < len; i++)
    {
        const auto rc = random_char();
        std::stringstream hexstream;
        hexstream << std::hex << rc;
        auto hex = hexstream.str();
        ss << (hex.length() < 2 ? '0' + hex : hex);
    }
    return ss.str();
}
int main()
{
    Server server;

    server.Post("/contacts/add", [](const httplib::Request &req, httplib::Response &res)
                {
                    try
                    {
                        // 反序列化
                        add_contacts::AddContactsRequest req_add;
                        if (!req_add.ParseFromString(req.body))
                        {
                            cout<<"反序列化失败"<<endl;
                            Exception e("反序列化失败");
                            throw e;
                        }
                        // 持久化通讯录-->这里不做了，直接就打印一遍
                        cout << "---------联系人信息" << "------" << endl;

                        cout << "联系人姓名: " << req_add.name() << endl;
                        cout << "联系人年龄: " << req_add.age() << endl;
                        for (int j = 0; j < req_add.phone_size(); j++)
                        {
                            const add_contacts::AddContactsRequest_Phone &phone = req_add.phone(j);
                            cout << "联系人电话" << j + 1 << ": " << phone.number();
                            // 联系人1:1234    (MP)
                            cout << "   (" << AddContactsRequest_Phone_PhoneType_Name(phone.type()) << ")" << endl;
                        }
                        // 序列化
                        add_contacts::AddContactsResponse resp;
                        resp.set_success(true);
                        resp.set_status(200);
                        resp.set_uid(generate_hex(10));
                        string resp_str;
                        
                        if (!resp.SerializeToString(&resp_str))
                        {
                            Exception e("序列化失败");
                            throw e;
                        }
                        res.status = 200;
                        res.body = resp_str;
                        res.set_header("Content_Type","/applaction/protobuf");
                    }
                    catch (Exception e)
                    {
                        add_contacts::AddContactsResponse resp;
                        res.status = 500;
                        resp.set_success(false);
                        resp.set_status(500);
                        resp.set_error_desc(e.what());
                        string resp_str;
                        if(resp.SerializeToString(&resp_str))
                        {
                            res.body = resp_str;
                            res.set_header("Content_Type","/applaction/protobuf");
                        }
                        cout <<"发生异常"<< e.what() << endl;
                    } 
                });
    server.listen("localhost", 8080);
    return 0;
}
// int main() {
//     httplib::Server svr;

//     // 简单的GET请求处理
//     svr.Get("/hello", [](const httplib::Request & /*req*/, httplib::Response &res) {
//         res.set_content("Hello, World!", "text/plain");
//     });

//     // 简单的POST请求处理
//     svr.Post("/post", [](const httplib::Request &req, httplib::Response &res) {
//         auto param = req.get_param_value("message");
//         std::string response = "Received message: " + param;
//         res.set_content(response, "text/plain");
//     });

//     std::cout << "Server listening on http://localhost:8080" << std::endl;
//     svr.listen("localhost", 8080);

//     return 0;
// }